<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SubjectSort extends Model
{
    protected $guarded = [];
    public static function treeData($collection, $pk = 'id', $pid = 'pid', $children = 'children', $root = 0)
    {
        $tree = [];
        foreach ($collection as $key => $val) {
            if ($val[$pid] == $root) {
                // 获取当前$pid所有子类
                unset($collection[$key]);
                if (count($collection) > 0) {
                    $childrenData = self::treeData($collection, $pk, $pid, $children, $val[$pk]);
                    if (count($childrenData) > 0) {
                        $val[$children] = $childrenData;
                    }
                }
                $tree[] = $val;
            }
        }
        return $tree;
    }
}
